package cn.cloudplug.core.manage.picture;

import android.content.Context;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Build;
import android.provider.DocumentsContract;
import android.provider.MediaStore;

/**
 * Created by pc on 2018/1/23.
 */

class PictureSearcher extends AsyncTask<Object,Void,PicInfoPacket> {

    private Callback callback;

    public PictureSearcher() {
    }


    public void execute(Context activity,Callback callback){
        execute(activity);
        this.callback=callback;
    }

    @Override
    protected PicInfoPacket doInBackground(Object...objects) {
        String[] column = getColumn();
        final Cursor cursor = ((Context)objects[0]).getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, column, null, null, column[1] + " desc");
        cursor.moveToFirst();
        int columnIndex ;
        String path;
        final boolean jianrong = Build.VERSION.SDK_INT>=19&& DocumentsContract.isDocumentUri(((Context)objects[0]), MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        if(jianrong) { //兼容andoid4.4版本;
            columnIndex = cursor.getColumnIndex(column[0]);
        }else{
            columnIndex = cursor.getColumnIndexOrThrow(column[0]);
        }
        final PicInfoPacket picInfoPacket=new PicInfoPacket();
        do{
            boolean b = check(cursor);
            if(b) {
                path = cursor.getString(columnIndex);
                picInfoPacket.add(path);
            }
        }while (cursor.moveToNext());
        return picInfoPacket;
    }

    private boolean check(Cursor cursor) {
        return true;
    }

    public String[] getColumn() {
        return new String[]{MediaStore.Images.Media.DATA, MediaStore.Images.Media.DATE_MODIFIED};
    }

    @Override
    protected void onPostExecute(PicInfoPacket picInfoPacket) {
        if (callback!=null){callback.onPostExecute(picInfoPacket);callback=null;}
    }

    @Override
    protected void onCancelled() {
        super.onCancelled();
        callback=null;
    }

}
